package cn.liuhuan.qiniu.controller;

import cn.liuhuan.qiniu.util.QiniuCloudUtil;
import cn.liuhuan.qiniu.web.JsonResult;
import cn.liuhuan.qiniu.web.ServiceCode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")
@Api(tags = "1.文件上传模块")
public class UploadController {

    @Autowired
    private QiniuCloudUtil qiniuCloudUtil;

    public UploadController() {
        log.info("创建控制器对象：UploadController");
    }

    @ApiOperation("上传用户头像")
    @ApiOperationSupport(order = 110)
    @PostMapping("/image/avatar")
    public JsonResult uploadAvatar(@RequestPart("file") MultipartFile image) throws IOException {
        log.info("UploadController:正在上传头像");
        return getFileName(image, "avatarImg");
    }

    @ApiOperation("上传笔记图片")
    @ApiOperationSupport(order = 120)
    @PostMapping("/image/note")
    public JsonResult uploadNoteImage(@RequestPart("file") MultipartFile image) throws IOException {
        log.info("UploadController:正在上传笔记图片");
        return getFileName(image, "noteImg");
    }

    @ApiOperation("上传笔记视频")
    @ApiOperationSupport(order = 130)
    @PostMapping("/video/note")
    public JsonResult uploadNoteVideo(@RequestPart("file") MultipartFile video) throws IOException {
        log.info("UploadController:正在上传笔记视频");
        String originalFilename = video.getOriginalFilename();
        if(originalFilename != null && originalFilename.endsWith(".mp4")){
            return getFileName(video, "noteVideo");
        }
        // 若不是mp4格式，则报错
        String message = "不正确的文件格式，只允许上传.mp4格式的视频文件";
        return JsonResult.fail(ServiceCode.ERROR_UPLOAD_EMPTY,message);
    }

    public JsonResult getFileName(MultipartFile image, String type) throws IOException {
        String firstName = image.getOriginalFilename();
        System.out.println("firstName = " + firstName);
        String[] split = firstName.split("\\.");
        String leftName = split[0];
        String fileName = leftName + UUID.randomUUID().toString();
        qiniuCloudUtil.upload(image, "resources/" + type + "/" + fileName);
        return JsonResult.ok("resources/" + type + "/" + fileName);
    }

}
